from flask import Blueprint, render_template, request

from apps.pojo.Entity import User, UserSchema,db
from apps.util.LayData import LayData

user_bp = Blueprint('user', __name__, url_prefix='/user')
user_schema = UserSchema(many=True)

@user_bp.route("/tolist")
def tolist():
    return render_template('user/list.html')

@user_bp.route("/toadd")
def toadd():
    return render_template('user/add.html')

@user_bp.route("/toupdate/<int:id>")
def toupdate(id):
    user=User.query.get(id)
    return render_template('user/update.html',user=user)

@user_bp.route("/todel/<int:id>")
def todel(id):
    user=User.query.get(id)
    db.session.delete(user)
    try:
        db.session.commit()
        return LayData.data2(0, msg="删除成功")
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '删除失败')


@user_bp.route("/dels",methods=['POST'])
def dels():
    ids = request.json.get('ids', [])
    print(ids)
    if not ids:
        return LayData.data2(400, msg="没有提供有效的用户ID")
    try:
        User.query.filter(User.id.in_(ids)).delete(synchronize_session=False)
        db.session.commit()
        return LayData.data2(0, msg="批量删除成功")
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '批量删除失败')

@user_bp.route("/addSave",methods=['POST'])
def addSave():
    username = request.form['username']
    password = request.form['password']
    user=User()
    user.username=username
    user.password=password
    try:
        db.session.add(user)
        db.session.commit()
        return LayData.data2(0,msg="添加成功")
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '添加失败')

@user_bp.route("/updateSave",methods=['POST'])
def updateSave():
    username = request.form['username']
    id = request.form['id']
    password = request.form['password']

    user=User.query.get(id)
    user.username=username
    user.password=password
    try:
        db.session.commit()
        return LayData.data2(0,'更新成功')
    except Exception as e:
        db.session.rollback()
        print(e)
        return LayData.data2(500, '更新失败')

@user_bp.route("/list")
def list():
    page=request.args.get("page",1,type=int)
    limit=request.args.get("limit",10,type=int)
    offset=(page-1)*limit
    userList=User.query.offset(offset).limit(limit).all()
    users=user_schema.dump(userList)
    #
    count=User.query.count();
    #拼凑格式
    response=LayData.data(0,"查询成功",count,users)
    return response


